package kn.pulldata.common;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttpUtils {
    // 创建一个单例的OkHttpClient，使用连接池
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectionPool(new ConnectionPool(
                    100, // 最大空闲连接数
                    5,  // 空闲连接存活时间
                    TimeUnit.MINUTES // 时间单位
            ))
            .connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
            .readTimeout(30, TimeUnit.SECONDS)    // 读取超时时间
            .writeTimeout(30, TimeUnit.SECONDS)   // 写入超时时间
            .build();
    // 辅助方法：创建一个FormBody.Builder实例
    public static FormBody.Builder formBodyBuilder() {
        return new FormBody.Builder();
    }
    // 发送GET请求
    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }

    // 发送POST请求，带JSON格式的body
    public static String postJson(String url, String json) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }

    // 发送POST请求，带表单数据和自定义请求头
    public static String postFormWithHeaders(String url, FormBody.Builder formBuilder, Headers.Builder headersBuilder) throws IOException {
        RequestBody formBody = formBuilder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .headers(headersBuilder.build()) // 添加自定义请求头
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }

}
